﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Xml;
using System.Reflection;
using Parallel3M.parallel3m.framework;

namespace Parallel3M.parallel3m.handler
{
    class CSharpClassRunHandler : ParallelHandler
    {
        public CSharpClassRunHandler()
        {
            handlerid = ParallelSystemHandlersConst.CSHARP_RUN_HANDLER;
            handlername = "csharp class run";
            handlerdefine = "<handler><class>...</class><parameters/></handler>";
        }

        
        public Hashtable getParameters(string payload_request)
        {
            Hashtable parameters = new Hashtable();
            // Create an XmlReader
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(payload_request);

            XmlNode requestNode = doc.ChildNodes[0];
            XmlAttributeCollection atts = requestNode.Attributes;
            foreach (XmlAttribute att in atts)            {
                parameters.Add(att.Name, att.Value);
            }

            XmlNodeList nodes = doc.ChildNodes[0].ChildNodes;
            foreach (XmlNode node in nodes)
            {
                parameters[node.Name] = node.InnerText;
            }
            return parameters;
        }

        public override string handle(ParallelPayload payload)
        {
            //
            Hashtable parameters = getParameters(payload.request);
            string classname = (String) parameters["function"];
            string assemblyInfo = (String)parameters["assembly"];
            Assembly assembly=null;
            if(!ParallelContext.libs.Contains(assemblyInfo)){
                string assemblyDll = ParallelContext.classpath + "\\" +  assemblyInfo + ".dll";
                assembly=Assembly.LoadFile(assemblyDll);
                ParallelContext.libs.Add(assemblyInfo,assembly);            
            }
            else{
                assembly=(Assembly)ParallelContext.libs[assemblyInfo];
            }
            
            ParalleClassRunInterface classInstance = (ParalleClassRunInterface)Activator.CreateInstance(assembly.GetType(classname));      
            string output = classInstance.function(parameters);
            return output;
        }
    }
}
